package com.game.tank.components;

import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.entity.SpawnData;
import com.almasb.fxgl.entity.component.Component;
import com.almasb.fxgl.time.LocalTimer;
import javafx.geometry.Point2D;
import javafx.util.Duration;

import java.util.HashMap;

/**
 * @author dylovedz
 */
public class TankComponent extends Component {

    private Dir dir;

    private final double INI_SPEED = 300;

    private double speed;

    private HashMap<Dir, Point2D> dirMap;
    private LocalTimer localTimer;

    /**
     * dir
     */
    enum Dir {
        UP, DOWN, LEFT, RIGHT;
    }

    @Override
    public void onUpdate(double tpf) {

        if (Dir.DOWN == dir || Dir.UP == dir) {
            entity.translateY(tpf * speed);
        }

        if (Dir.LEFT == dir || Dir.RIGHT == dir) {
            entity.translateX(tpf * speed);
        }
        speed = 0;
        /*speed = (int) speed * 0.9;
        if (Math.abs(speed) < 1) {
            speed = 0;
        }*/
    }

    @Override
    public void onAdded() {
        localTimer = FXGL.newLocalTimer();
        dirMap = new HashMap<>(4);
        dirMap.put(Dir.UP, new Point2D(0, -1));
        dirMap.put(Dir.DOWN, new Point2D(0, 1));
        dirMap.put(Dir.LEFT, new Point2D(-1, 0));
        dirMap.put(Dir.RIGHT, new Point2D(1, 0));
        dir = Dir.UP;
        speed = 0;
    }

    public void moveUp() {

        entity.setRotation(0);
        dir = Dir.UP;
        speed = -INI_SPEED;
    }

    public void moveDown() {

        entity.setRotation(180);
        dir = Dir.DOWN;
        speed = INI_SPEED;
    }

    public void moveLeft() {

        entity.setRotation(270);
        dir = Dir.LEFT;
        speed = -INI_SPEED;
    }

    public void moveRight() {

        entity.setRotation(90);
        dir = Dir.RIGHT;
        speed = INI_SPEED;
    }

    public void shoot() {

        if (!localTimer.elapsed(Duration.seconds(.25))) {
            return;
        }
        SpawnData data = new SpawnData(entity.getCenter().getX(), entity.getCenter().getY());
        data.put("point2d", dirMap.get(dir));
        FXGL.getGameWorld().spawn("bullet", data);
        FXGL.play("shoot.wav");
        localTimer.capture();
    }
}
